Skip to main content

Python

These rule examples will help your developers to write better python code. Use them as inspiration to create your own guideline repository.

## Security
- Always validate permissions using decorators or middleware functions.
# Example of a permission validation decorator
@requires_permission([PERMISSIONS.VIEW_DATA, PERMISSIONS.EDIT_DATA])
def some_view_function():
# View logic here
- Always validate user input, particularly on web endpoints, to prevent injection attacks. Use parameterized queries for database interactions.
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))

## Configuration
- Maintain a clear separation between configuration and code logic. Use config files (config.yaml, .env) or environment variables for all configurable options.
- Use Python's built-in logging module (logging) and avoid print() statements in production code. Use DEBUG for detailed diagnostic information, INFO for general operational messages, ERROR for failures.

## Code
- Use snake_case for function names, and PascalCase for class definitions.
- Prefer asyncio for asynchronous programming rather than callbacks.
import asyncio
async def fetch_data():
response = await some_async_call()
return response
- Use type annotations to make your code more readable and maintainable
- For large data sets or streaming, use Python's generator expressions to handle memory efficiently.
- Use with statements when dealing with file I/O or database connections to ensure proper resource management.